package com.agilegroup.crm.database;

import java.util.ArrayList;
import java.util.List;

import com.agilegroup.crm.model.ContactStatus;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ContactDAO {

	private SQLiteDatabase db;
	private AgileSQLiteHelper dbHelper;
	
	public ContactDAO(Context context) {
		dbHelper = new AgileSQLiteHelper(context);
	    db = dbHelper.getWritableDatabase();
	}
	public void close() {
	       db.close();
	   }
	
	 public void createContact(String contactId,String isSync) {
	       ContentValues contentValues = new ContentValues();
	       contentValues.put("contactId", contactId);
	       contentValues.put("isSync", isSync);
	       db.insert("contacts", null, contentValues);
	   }
	 public void deleteTodo(int id) {
	       db.delete("contacts", "_id = " + id, null);
	   }
	 
		public ContactStatus getContact(String contactId) {
			String[] tableColumns = new String[] {"_id","contactId","isSync"};
			Cursor cursor = db.query("contacts", tableColumns, "contactId" + "=?",
					new String[] {contactId}, null, null, null, null);
			if (cursor != null)
				cursor.moveToFirst();
			   ContactStatus contactStatus = new ContactStatus();
	           contactStatus.setId(cursor.getInt(0));
	           contactStatus.setContactId(cursor.getString(1));
	           contactStatus.setIsSync(cursor.getString(2));
			return contactStatus;
		}
	 
	 public List<ContactStatus> getContacts(){
		 List<ContactStatus> contactList = new ArrayList<ContactStatus>();
		 
		 String[] tableColumns = new String[] {"_id","contactId","isSync"};
		 
		 Cursor cursor = db.query("contacts", tableColumns, null, null, null, null, null);
	     cursor.moveToFirst();
	     
	     while (!cursor.isAfterLast()) {
	           ContactStatus contactStatus = new ContactStatus();
	           // Take values from the DB
	           contactStatus.setId(cursor.getInt(0));
	           contactStatus.setContactId(cursor.getString(1));
	           contactStatus.setIsSync(cursor.getString(2));
	 
	           // Add to the DB
	           contactList.add(contactStatus);
	 
	           // Move to the next result
	           cursor.moveToNext();
	       }
	 
	       return contactList;
	 }
	 public boolean checkContactIsSynced(String contactId){
		 boolean isSynced=false;
		 ContactStatus contactStatus = getContact(contactId);
		 if(contactStatus.getContactId().equals(contactId)){
			 isSynced=true;
		 }
		 else{
				isSynced=false;
			}
		 return isSynced;
	 }
}
